package com.hengli.controller.user;

import com.hengli.constant.StatusConstant;
import com.hengli.entity.Wine;
import com.hengli.result.Result;
import com.hengli.service.WineService;
import com.hengli.vo.WineVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userWineController")
@RequestMapping("/user/wine")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class WineController {
    @Autowired
    private WineService wineService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<WineVO>> list(Long categoryId) {
        // 构造redis中的key，规则：wine_分类id
        String key = "wine_" + categoryId;

        // 查询Redis中是否存在酒品数据
        List<WineVO> list = (List<WineVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0){
            // 如果存在，直接返回，无需查询数据库
            return Result.success(list);
        }

        Wine wine = new Wine();
        wine.setCategoryId(categoryId);
        wine.setStatus(StatusConstant.ENABLE);//查询起售中的酒品

        // 如果不存在，查询数据库，将查询到的数据放入redis中
        list = wineService.listWithSpecification(wine);
        redisTemplate.opsForValue().set(key, list) ;

        return Result.success(list);
    }

}
